//
//  MultiSegmentSplitView.m
//  MultiSegmentController
//
//  Created by ET|冰琳 on 16/5/24.
//  Copyright © 2016年 Binglin. All rights reserved.
//

#import "MultiSegmentSplitView.h"
#import "SplitTableView.h"

@interface MultiSegmentSplitView ()<SegmentSelectProtocol, SplitTableViewDataSource, SplitTableViewDelegate, UIGestureRecognizerDelegate>

@property (nonatomic) BIMultiSegmentControl *segmentControl;
@property (nonatomic, strong) NSMutableArray  *segmentItemViews;
@property (nonatomic, strong) UIView *showContainer;
@property (nonatomic, strong) UIView  *showMaskView;
@property (nonatomic, strong) UIView  *dismissMaskView;

@end

@implementation MultiSegmentSplitView

- (instancetype)initWithSegmentControl:(BIMultiSegmentControl *)control{
    if (self = [super initWithFrame:control.bounds]) {
        self.segmentControl = control;
        self.segmentControl.delegate = self;
        self.segmentControl.sameIgnore = NO;
        
        [self addSubview:control];
        
        [self setUpSplitView];
        
        self.showContainer = [[UIView alloc] initWithFrame:CGRectMake(0,
                                                                      self.segmentControl.frame.size.height,
                                                                      self.segmentControl.frame.size.width,
                                                                      0)];
        [self addSubview:self.showContainer];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];
        [self.showContainer addGestureRecognizer:tap];
        tap.delegate = self;
        
        self.showContainer.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
        
        self.showMaskView = [[UIView alloc] initWithFrame:CGRectMake(0,
                                                                     self.segmentControl.frame.size.height,
                                                                     self.segmentControl.frame.size.width,
                                                                     0)];
        self.showMaskView.backgroundColor = [UIColor whiteColor];

        
        self.dismissMaskView = [[UIView alloc] initWithFrame:CGRectMake(0,
                                                                     self.segmentControl.frame.size.height,
                                                                     self.segmentControl.frame.size.width,
                                                                     0)];
        self.dismissMaskView.backgroundColor = [UIColor whiteColor];

    }
    return self;
}

- (void)setUpSplitView{
    
    self.segmentItemViews = [NSMutableArray arrayWithCapacity:self.segmentControl.segmentItems.count];
    
    for (int i = 0; i < self.segmentControl.segmentItems.count; i ++) {
        
        SplitTableView *split = [[SplitTableView alloc] initWithFrame:CGRectMake(0,0,
                                                                                 self.segmentControl.frame.size.width,
                                                                                 self.frame.size.height - self.segmentControl.frame.size.height)];
        split.dataSource = self;
        split.delegate   = self;
        split.backgroundColor = [UIColor whiteColor];
        
        [self.segmentItemViews addObject:split];
    }
}

#pragma mark - action
- (void)tapped:(UITapGestureRecognizer *)tap{
    
    if (self.showContainer.frame.size.height > 0) {
        [self.segmentControl reset];
        [self segmentControlDeSelectIndex:self.segmentControl.selectIndex];
    }
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    id<SegmentItemProtocol> item = self.segmentControl.segmentItems[self.segmentControl.selectIndex];
    if (item.selected) {
        
        if (CGRectContainsPoint([self.segmentItemViews[self.segmentControl.selectIndex] frame], [gestureRecognizer locationInView:self.showContainer])) {
            return NO;
        }
    }
    return YES;
}

#pragma mark - SegmentSelectProtocol
- (void)segmentControlDidSelectIndex:(NSInteger)index{
    
    UIScrollView *superScrollView ;
    for (UIView *view = self.superview; view; view = view.superview) {
        if ([view isKindOfClass:[UIScrollView class]]) {
            superScrollView = (UIScrollView *)view;
            break;
        }
    }
    
    if (superScrollView) {
        
        CGRect frame = [self convertRect:self.bounds toView:self.dropContainer];
        
        NSLog(@"%@", NSStringFromUIEdgeInsets(superScrollView.contentInset));
        if (frame.origin.y > 0.001f) {
            CGRect selfDestination = [self convertRect:self.bounds toView:superScrollView];
            [superScrollView setContentOffset:CGPointMake(0, CGRectGetMinY(selfDestination) - superScrollView.contentInset.top) animated:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self showViewAtIndex:index];
            });
        }else{
            [self showViewAtIndex:index];
        }
        return;
    }
    
    [self showViewAtIndex:index];

}

- (void)showViewAtIndex:(NSInteger)index{
    
    [self.dropContainer addSubview:self.showContainer];
    
    SplitTableView *viewToAdd = self.segmentItemViews[index];
    
    [viewToAdd reloadAllComponents];
    
    CGFloat destinationHeight = self.dropContainer.frame.size.height/3.0 * 2;
    if ([self.dataSource respondsToSelector:@selector(heightForSplitViewAtSegmentIndex:)]) {
        destinationHeight = [self.dataSource heightForSplitViewAtSegmentIndex:index];
    }
    
    CGRect f = viewToAdd.frame;
    f.size.height = destinationHeight;
    CGRect convertF = [viewToAdd convertRect:f toView:self.dropContainer];
    
    
    CGRect selfSuperFrame = [self convertRect:self.bounds toView:self.dropContainer];
    
    CGRect fContainer = self.showContainer.frame;
    fContainer.origin.y = CGRectGetMaxY(selfSuperFrame);
    fContainer.size.height = self.dropContainer.frame.size.height - fContainer.origin.y;
    
    self.showContainer.frame = fContainer;
    
    [self.showContainer addSubview:viewToAdd];
    
    if (f.size.height > CGRectGetHeight(self.dropContainer.frame) - CGRectGetMaxY(convertF)) {
        f.size.height = CGRectGetHeight(self.dropContainer.frame) - CGRectGetMaxY(convertF);
    }
    
    viewToAdd.alpha = 1;
    viewToAdd.frame = f;
    
    self.showMaskView.frame = ({ CGRect f = viewToAdd.bounds;
        f.size.height = 0;
        f;
    });
    [viewToAdd addSubview:self.showMaskView];
    viewToAdd.maskView = self.showMaskView;
    
    self.showContainer.alpha = 1.0;
    
    [UIView animateWithDuration:0.2 animations:^{
        self.showMaskView.frame = viewToAdd.bounds;
    }];
}

- (void)segmentControlDeSelectIndex:(NSInteger)index{
    
    UIView *viewToHide = self.segmentItemViews[index];
    
    self.dismissMaskView.frame = viewToHide.bounds;
    [viewToHide addSubview:self.dismissMaskView];
    viewToHide.maskView = self.dismissMaskView;

    
    CGRect f = viewToHide.frame;
    f.size.height = 0;
        
    [UIView animateWithDuration:0.2 animations:^{
        self.dismissMaskView.frame = f;
        viewToHide.alpha = 0;
        if (self.segmentControl.selectIndex == index) {
            self.showContainer.alpha = 0;
        }
    } completion:^(BOOL finished) {
        [viewToHide removeFromSuperview];
        if (self.segmentControl.selectIndex == index) {
             [self.showContainer removeFromSuperview];
        }
    }];
}


#pragma mark - SplitTableViewDataSource
- (NSInteger)numberOfComponentsInsplitTableView:(SplitTableView *)splitTableView{
    NSInteger index = [self.segmentItemViews indexOfObject:splitTableView];
    if ( ![self.dataSource respondsToSelector:@selector(componentNumberAtSegmentIndex:)]) {
        return 1;
    }
    return [self.dataSource componentNumberAtSegmentIndex:index];
}

- (NSInteger)splitTableView:(SplitTableView *)splitTableView numberOfRowsInComponent:(NSInteger)component{
    NSInteger index = [self.segmentItemViews indexOfObject:splitTableView];
    return [self.dataSource numberOfRowsInComponent:component AtSegmentIndex:index];
}

- (UITableViewCell *)splitTableView:(SplitTableView *)splitView CellInTableView:(UITableView *)tableView ForRow:(NSInteger)row forComponent:(NSInteger)component{
    NSInteger index = [self.segmentItemViews indexOfObject:splitView];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.contentView.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = [UIFont systemFontOfSize:14];
    }
    
    UIView *accessoryView = [cell.contentView viewWithTag:234];
    if (accessoryView == nil) {
        UIImageView *imageIndicator = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"new_duigou"]];
        imageIndicator.tag = 234;
        [cell.contentView addSubview:imageIndicator];
        CGRect fImage = imageIndicator.frame;
        fImage.origin.x = cell.frame.size.width - 15 - CGRectGetWidth(fImage);
        fImage.origin.y = CGRectGetHeight(cell.frame)/2.0 - CGRectGetHeight(fImage)/2.0;
        accessoryView = imageIndicator;
        accessoryView.hidden = true;
    }
    
    tableView.backgroundColor = [UIColor clearColor];
    
    if ([self.dataSource respondsToSelector:@selector(titleForCellAtSegmentIndex:component:row:)]) {
        cell.textLabel.text = [self.dataSource titleForCellAtSegmentIndex:index component:component row:row];
    }
    
    //选中 未选中 状态设置
    if (self.dataSource && [self.dataSource respondsToSelector:@selector(isSelectForCellAtSegmentIndex:component:row:)]) {
        BOOL isSelect = [self.dataSource isSelectForCellAtSegmentIndex:index component:component row:row];
        
        if (isSelect) {
            cell.textLabel.textColor = [UIColor blackColor];
            accessoryView.hidden = NO;
        }else{
            cell.textLabel.textColor = [UIColor lightGrayColor];
            accessoryView.hidden = YES;
        }
        
        //多个component第一个tableView背景为灰色
        if (isSelect == NO && component == 0 && [self numberOfComponentsInsplitTableView:splitView] > 1) {
            cell.contentView.backgroundColor = [UIColor colorWithRed:245.f/255.f green:242.f/255.f blue:242.f/255.f alpha:1.f];
            accessoryView.hidden = YES;
            tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        }else{
            cell.contentView.backgroundColor = [UIColor whiteColor];
        }
        
    }else{
        if (component == 0 && [self numberOfComponentsInsplitTableView:splitView] > 1) {
            cell.contentView.backgroundColor = [UIColor colorWithRed:245.f/255.f green:242.f/255.f blue:242.f/255.f alpha:1.f];
        }else{
            cell.contentView.backgroundColor = [UIColor whiteColor];
        }
    }
    
    //cell界面设置
    if (self.dataSource && [self.dataSource respondsToSelector:@selector(configurationCell:AtSegmentIndex:component:row:)]) {
        [self.dataSource configurationCell:cell AtSegmentIndex:index component:component row:row];
    }
    
    return cell;
}


#pragma mark - SplitTableViewDelegate

- (void)splitTableView:(SplitTableView *)splitTableView didSelectComponent:(NSInteger)component row:(NSInteger)row{
    NSInteger index = [self.segmentItemViews indexOfObject:splitTableView];
    [self.dataSource didSelectAtSegmentIndex:index component:component row:row];
    
    [splitTableView reloadAllComponents];
    
    //当仅一列(一个component)时 默认选择后即消失
    //当有多列时 默认选择最后一个component时消失
    
    if ([self.dataSource respondsToSelector:@selector(shouldDismissAtSegmentIndex:component:row:)]) {
        BOOL dismiss = [self.dataSource shouldDismissAtSegmentIndex:index component:component row:row];
        if (dismiss) {
            [self hideSegmentSplitViews];
        }
    }else{
        NSInteger componentNumber = [self numberOfComponentsInsplitTableView:splitTableView];
        if (componentNumber == 1 || (componentNumber > 1  && component == componentNumber - 1)  ) {
            [self hideSegmentSplitViews];
        }
    }
    
    if (self.changeSegmentTitleWhenSelectRow
        && [self.dataSource respondsToSelector:@selector(titleForCellAtSegmentIndex:component:row:)]
        && ([self numberOfComponentsInsplitTableView:splitTableView] - 1 == component)) {
        [self setSegmentTitle:[self.dataSource titleForCellAtSegmentIndex:index component:component row:row] AtIndex:index];
    }
}

- (void)hideSegmentSplitViews{
    id<SegmentItemProtocol> item = self.segmentControl.segmentItems[self.segmentControl.selectIndex];
    if (item.selected) {
        [[self segmentControl] reset];
        [self segmentControlDeSelectIndex:self.segmentControl.selectIndex];
    }
}

- (void)setSegmentTitle:(NSString *)title AtIndex:(NSInteger)index{
    UIButton *btn = self.segmentControl.segmentItems[index];
    [btn setTitle:title forState:UIControlStateNormal];
}

- (void)reloadViewAtSegmentIndex:(NSInteger)index{
    SplitTableView *split = [self.segmentItemViews objectAtIndex:index];
    [split reloadAllComponents];
}

@end
